package sort.test148;

import listbyorder.utils.ListNode;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/7/19 9:34
 */
public class Solution1 {

    // 归并排序
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) return head;
        // 快慢指针将链表分成两段
        ListNode s = head, f = head;
        while (f.next != null && f.next.next != null) {
            s = s.next;
            f = f.next.next;
        }
        ListNode right = sortList(s.next);
        s.next = null;
        ListNode left = sortList(head);
        // 合并两个链表
        return mergeTwoLists(left, right);
    }

    private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode t = dummy;
        while (l1 != null || l2 != null) {
            if (l1 == null) {
                t.next = l2;
                l2 = l2.next;
            } else if (l2 == null) {
                t.next = l1;
                l1 = l1.next;
            } else {
                if (l1.val <= l2.val) {
                    t.next = l1;
                    l1 = l1.next;
                } else {
                    t.next = l2;
                    l2 = l2.next;
                }
            }
            t = t.next;
        }
        return dummy.next;
    }
}
